package com.castile.oa;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @description: 从Jar包中加载指定的类
 * @author: Castile
 * @create: 2024-04-08 23:20
 * @Version 1.0
 **/
public class OADemoFromJarFile {
    public static void main(String[] args) throws Exception {
        Double salary = 2000.0;
        Double money;
        String jarPath = "F:\\myfiles\\learning\\castile-common-lib\\class-loader-case\\lib\\external-module-1.0-SNAPSHOT.jar";
        // 从.myclass 文件中加载对象
        SalaryJarClassLoader salaryClassLoader = new SalaryJarClassLoader(jarPath);
        while (true) {
            money = calcMoney(salary, salaryClassLoader);
            System.out.println("实际到手工资为：" + money);
            TimeUnit.MILLISECONDS.sleep(1000);
        }
    }


    /**
     * 使用外部Jar包来实现计算逻辑
     *
     * @param salary
     * @return
     */
    private static Double calcMoney(Double salary, ClassLoader classLoader) throws Exception {
        // 运行时加载外部jar。加载一次就不能再更新。jar包删掉也不行
        Class<?> aClass = classLoader.loadClass("com.castile.external.SalaryCalculator");
        Object obj = aClass.newInstance();
        Method cal = aClass.getMethod("cal", Double.class);
        return (Double) cal.invoke(obj, salary);
    }
}
